package javango.forms.fields;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.google.inject.Inject;

import javango.forms.widgets.ChoicesWidget;
import javango.forms.widgets.SelectWidget;
import javango.forms.widgets.Widget;
import javango.forms.widgets.WidgetFactory;

public class SelectField extends FieldBase implements ChoiceField {
	
	@Inject
	public SelectField(WidgetFactory widgetFactory) {
		super(widgetFactory);
		setWidget(SelectWidget.class);
	}

	@Inject
	public SelectField(WidgetFactory widgetFactory, Map<String, Object> choices) {
		super(widgetFactory);
		this.choices = choices;
	}

	protected Map<String, Object> choices;
	
	public long getChoiceCount() {
		return choices == null ? 0 : choices.size();
	}

	public Map<String, Object> getChoices() {
		return choices;
	}

	public SelectField setChoices(Map<String, Object> choices) {
		this.choices = choices;
		Widget widget = super.getWidget();
		if (widget instanceof ChoicesWidget) {			
			((ChoicesWidget)widget).setField(this);
		}
		return this;
	}
	
	@Override
	public Field setWidget(Widget widget) {
		if (widget instanceof ChoicesWidget) {
			((ChoicesWidget)widget).setField(this);
		}

		return super.setWidget(widget);
	}

	@Override
	public Object clean(String[] value, Map<String, String> errors) {
		Object myValue = super.clean(value, errors);
		if (myValue == null || (myValue instanceof String && StringUtils.isBlank((String)myValue))) {
			return myValue; // super should have flagged errors,  and cleaned correctly
		}
		Map<String, Object> localChoices = getChoices();
		if (localChoices == null)   {
			errors.put(this.name, "Select a valid choice.  No choices are available.");
		} else if (!localChoices.containsKey(myValue)) {
			errors.put(this.name, "Select a valid choice.  That choice is not one of the available choices.");
		}
		
		return myValue;
	}	
	
}
